﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MissionEditor.EventUI
{
    public partial class UnitSpawn : UserControl, IEventUI
    {
        Event activeEvent;
        byte numberOfUnits;

        public UnitSpawn(Event activeEvent)
        {
            this.activeEvent = activeEvent;
            InitializeComponent();
            xTextBox.Text = BitConverter.ToUInt32(activeEvent.raw, 0).ToString();
            yTextBox.Text = BitConverter.ToUInt32(activeEvent.raw, 4).ToString();
            numberOfUnits = activeEvent.raw[14];
            sideComboBox.SelectedIndex = activeEvent.raw[15];
            unknownR1.Text = activeEvent.raw[18].ToString();
            tableLayoutPanel1.Controls.Clear();
            tableLayoutPanel1.RowCount = numberOfUnits;

            for (int i = 0; i < numberOfUnits; i++)
            {
                ComboBox comboBox = new ComboBox();
                comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                comboBox.Items.AddRange(Mission.Units);
                comboBox.SelectedIndex = activeEvent.raw[47 + i];
                tableLayoutPanel1.Controls.Add(comboBox, 0, i);    
            }
        }
        public void Apply()
        {
            BitConverter.GetBytes(Convert.ToUInt32(xTextBox.Text)).CopyTo(activeEvent.raw, 0);
            BitConverter.GetBytes(Convert.ToUInt32(yTextBox.Text)).CopyTo(activeEvent.raw, 4);
            activeEvent.raw[15] = (byte)sideComboBox.SelectedIndex;
            activeEvent.raw[18] = Convert.ToByte(unknownR1.Text);

            activeEvent.raw[14] = numberOfUnits;
            for (int i = 0; i < numberOfUnits; i++)
            {
                activeEvent.raw[47 + i] = (byte)((ComboBox)tableLayoutPanel1.Controls[i]).SelectedIndex;
            }
        }

        private void addUnitButton_Click(object sender, EventArgs e)
        {
            if (numberOfUnits < 25)
            {
                numberOfUnits++;
                
                ComboBox comboBox = new ComboBox();
                comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                comboBox.Items.AddRange(Mission.Units);
                comboBox.SelectedIndex = 0;
                tableLayoutPanel1.Controls.Add(comboBox, 0, numberOfUnits);
                tableLayoutPanel1.RowCount = numberOfUnits;
            }
        }

        private void deleteLastUnitButton_Click(object sender, EventArgs e)
        {
            if(numberOfUnits > 1)
            {
                numberOfUnits--;
                
                tableLayoutPanel1.Controls.RemoveAt(numberOfUnits);
                tableLayoutPanel1.RowCount = numberOfUnits;
            }
        }
    }
}
